package com.imooc.ad.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class PreRequestFilter extends ZuulFilter {

    //过滤器类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //过滤器执行顺序，数字越小级别越高
    @Override
    public int filterOrder() {
        return 0;
    }

    //是否需要执行过滤器
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //过滤器执行逻辑：计算执行时间，pre过滤器记录开始时间
    @Override
    public Object run() throws ZuulException {

        //请求上下文，将当前请求时间传递给另一个过滤器
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.set("startTime", System.currentTimeMillis());

        return null;
    }
}
